﻿using System;
using System.Collections.Generic;
using System.Data;
using MedicService.Domain.Directory;
using MedicService.Domain.Directory.Simple;
using MedicService.Server.Factory.Directory.Simple;
using MedicService.Server.Factory.Generic;

namespace MedicService.Server.Factory.Directory {
    public class SpecialityFactory : DirectoryFactory<Speciality> {
        public SpecialityFactory() : base("Speciality", "number") { }

        protected override void FillEntity(Speciality entity, DataRow myDataRow) {
            entity.Id = (int)myDataRow["id"];
            entity.Title = (string)myDataRow["title"];

            entity.Number = (int)myDataRow["number"];
            //entity.ClassSpecialisation = new ClassSpecialisationFactory().Load(myDataRow["ClassSpecialisationId"]);
            entity.ClassSpecialisations = new List<ClassSpecialisation>();
            List<int> idList = ParseIdList(myDataRow["ClassSpecList"] as string);
            var classSpecialisationFactory = new ClassSpecialisationFactory();
            foreach (var id in idList) {
                entity.ClassSpecialisations.Add(classSpecialisationFactory.Load(id));
            }
        }

        protected override Speciality CreateEntity() {
            return new Speciality();
        }

        protected override string GetInsertQuery(Speciality entity) {
            string q = "INSERT INTO [Speciality]" +
                       "           ([title]" +
                       "           ,[ClassSpecList]" +
                       "           ,[number])" +
                       "     VALUES" +
                       "           (" + Nullable(entity.Title) +
                       "           ," + Nullable(entity.ClassSpecialisations) +
                       "           , 0);" +
                       "     ";
            return q;
        }

        protected override string GetUpdateQuery(Speciality entity) {
            Speciality old = Load(entity.Id);
            string q = "";
            if (old.Number < entity.Number) {
                //q += " UPDATE [Speciality] SET number = number-1 WHERE number > " + old.Number + " AND number < " + entity.Number;
                q += " UPDATE [Speciality] SET number = number-1 WHERE number <= " + entity.Number + " AND number > " + old.Number + ";";
            }
            if (old.Number > entity.Number) {
                q += " UPDATE [Speciality] SET number = number+1 WHERE number < " + old.Number + " AND number >= " + entity.Number;
            }
            q += " UPDATE [Speciality]" +
                       "   SET [title] = " + Nullable(entity.Title) +
                       "      ,[ClassSpecList] = " + Nullable(entity.ClassSpecialisations) +
                       "      ,[number] = " + Nullable(entity.Number) +
                       " WHERE id=" + entity.Id + ";";
            return q;
        }

    }

}